package com.monas.server.parser.linux;

import java.sql.Types;
import java.util.LinkedList;

import com.monas.server.parser.MonasHeader;
import com.monas.server.parser.MonasParser;

public class DfH extends MonasParser {

	public DfH() {
		super(new MonasHeader(Types.VARCHAR, "filesystem"), new MonasHeader(
				Types.INTEGER, "disk_size"), new MonasHeader(Types.INTEGER,
				"disk_used"), new MonasHeader(Types.INTEGER, "disk_avail"),
				new MonasHeader(Types.INTEGER, "disk_used_percent"),
				new MonasHeader(Types.VARCHAR, "disk_mounted_on"));
	}

	@Override
	public boolean isNextBegin(String line) {
		return line.indexOf("df -h") > 0;
	}

	@Override
	public boolean isFinish(String line) {
		return line.indexOf("@") > 0 || line.indexOf("]") > 0
				|| line.indexOf("~") > 0;
	}

	@Override
	public String getTableName() {
		return "df_h";
	}

	@Override
	public LinkedList<Object[]> getRecords() {
		LinkedList<Object[]> records = new LinkedList<Object[]>();
		int size_idx = 0;
		String fs = null;

		if (getLines().size() > 0) {
			for (String line : getLines()) {

				if (line.startsWith("Filesystem")) {
					size_idx = line.indexOf("Size ");
					continue;
				}

				if (size_idx > 0) {
					String[] fields = line.trim().split("\\s+");
					if (fields[0].length() > size_idx && fields.length == 1) {
						fs = fields[0];
						continue;
					}

					String[] objects = new String[6];
					if (fs != null) {
						for (int i = 0; i < objects.length; i++) {
							if (i > 0) {
								objects[i] = getValue(fields[i - 1]);
							} else {
								objects[0] = fs;
								fs = null;
							}
						}
					} else {
						for (int i = 0; i < objects.length; i++) {
							if (i > 0) {
								objects[i] = getValue(fields[i]);
							} else {
								objects[i] = fields[i];
							}
						}
					}

					records.add(objects);
				}
			}
		}
		return records;
	}

	private String getValue(String field) {
		int idx = field.indexOf("%");
		if (idx > 0) {
			return field.substring(0, idx);
		}

		if (!field.startsWith("/") && !field.equals("0")) {

			String size = null;

			if (Character.isLetter(field.charAt(field.length() - 1))) {
				size = field.substring(field.length() - 1);
			}

			if (size == null) {
				return "0";
			}

			String value = field.substring(0, field.length() - 1);

			if (size.equals("K")) {
				return "0";
			}

			if (size.equals("M")) {
				// return value;
				return new Integer((int) (Double.valueOf(value) * 1))
						.toString();
			}

			if (size.equals("G")) {
				return new Integer((int) (Double.valueOf(value) * 1000))
						.toString();
			}
		}
		return field;
	}

}
